<?php
namespace Helper\Controller;

use Think\Controller;

/*
 * 注意提示：
 * 此文件为通用上传类,但是当使用七牛云时或者其他其他云存储开启私有空间时
 * 注意图片则需要加上样式访问,其他非图片文件则需要token访问。
 *
 * **/
class UploadController extends Controller {

    const DEFAULT_MAX_SIZE = '2097152';  // 2M
    const ALLOW_PATH_LIST = 'attachments,';
    const TYPE_IAMGE = 'image';
    const TYPE_VIDEO = 'video';
    const TYPE_AUDIO = 'audio';
    const TYPE_FILE  = 'file';
    const STORAGE_QINIU = 'Qiniu';
    const STORAGE_LOCAL = 'Local';

    protected $upload_setting;

    function _initialize() {
        $admin_id = x_get_admin_id();
        $user_id  = x_get_user_id();
        if (empty($admin_id) && empty($user_id)) {
            exit("非法上传");
        }
        $this->upload_setting = x_get_upload_setting();
    }

    public function get_all_allowed_exts($filetype) {

        $file_types = array(
            'image'=>array('title'=>'Image files','extensions'=>$this->upload_setting['image']['extensions']),
            'video'=>array('title'=>'Video files','extensions'=>$this->upload_setting['video']['extensions']),
            'audio'=>array('title'=>'Audio files','extensions'=>$this->upload_setting['audio']['extensions']),
            'file'=>array('title'=>'Custom files','extensions'=>$this->upload_setting['file']['extensions'])
        );
        if (isset($file_types[$filetype])) {
            return array_unique(explode(',', $file_types[$filetype]['extensions']));
        }

        return array();

    }

    //AJAX 方式提交方式的上传
    public function uploadaJAX() {

        $result = $this->uploadFile(
            I('get.app', ''),
            I('get.filetype', 'image')
        );
        $this->ajaxReturn($result);
    }

    //文件上传
    public function uploadFile($app, $type = 'image') {

        //1.get_all_allowed_exts
        $all_allowed_exts = $this->get_all_allowed_exts($type);

        //2.获取图片允许的后缀
        $image_extensions = ($type == self::TYPE_IAMGE ?
            $all_allowed_exts : $this->get_all_allowed_exts('image'));


        if (IS_POST) {

            $file_extension = x_get_file_extension($_FILES['file']['name']);

            //文件上传大小
            $upload_max_filesize = $this->upload_setting['upload_max_filesize'][$file_extension];
            $upload_max_filesize = empty($upload_max_filesize)
                ? SELF::DEFAULT_MAX_SIZE : $upload_max_filesize;

            //上传目录
            if(!in_array($app, C('MODULE_ALLOW_LIST'))
                && !in_array($app, explode(',', self::ALLOW_PATH_LIST))){
                $app = 'default';
            }else{
                $app = strtolower($app);
            }
            $save_path = $app . '/' . date('Ymd') . '/';

            //上传处理类
            $config = array(
                'rootPath'   => './'.C("X_UPLOAD_PATH"),
                'savePath'   => $save_path,
                'maxSize'    => $upload_max_filesize,
                'saveName'   => array('uniqid',''),
                'exts'       => $all_allowed_exts,
                'autoSub'    => false,
            );

            $upload = new \Think\Upload($config);//
            $info = $upload->upload();
            //开始上传
            if ($info) {
                //上传成功
                $filename = $_FILES['file']['name'];
                //写入附件数据库信息

                //单文件
                $file_data = array_shift($info);

                if (!empty($file_data['url'])) { //存在url,为云存在

                    $url = $file_data['url'];

                    //七牛云设置处理
                    if (C('FILE_UPLOAD_TYPE') == self::STORAGE_QINIU) {
                        $storage_setting = x_get_config_by_key(\Admin\Controller\SettingController::STORAGE_KEY);
                        $qiniu_setting = $storage_setting['Qiniu']['setting'];
                        $url = preg_replace(array('/^https/', '/^http/'), $qiniu_setting['protocol'], $url);

                        //开启图片原图保护（加水印，开启原图保护相当于图片是私有）
                        if ($type == self::TYPE_IAMGE || in_array($file_extension, $image_extensions)) {
                            if ($qiniu_setting['enable_picture_protect']) {
                                $preview_url = $url . $qiniu_setting['style_separator'] . $qiniu_setting['styles']['thumbnail300x300'];
                                $url = $url . $qiniu_setting['style_separator'] . $qiniu_setting['styles']['watermark'];
                            }

                        } else { //非图片情况下，无预览,则url下载链接
                            $preview_url = '';
                            $url = x_get_file_download_url($file_data['savepath'] . $file_data['savename'], 3600*24*365*50);//过期时间设置为50年
                        }
                    }
                } else {
                    //本地存储方式
                    $url = C("TMPL_PARSE_STRING.__UPLOAD__") . $save_path . $file_data['savename'];
                    $preview_url = $url;
                }


                $file_path = $save_path . $file_data['savename'];
                //preview_url   预览的url
                //url  实际访问的url
                //file_path 存储路径 相对路径

                return array('preview_url'=>$preview_url,'filepath'=>$file_path,'url'=>$url,'name'=>$filename,'status'=>1,'message'=>'success');
            } else {

                return array('name'=>'','status'=>0,'message'=>$upload->getError());

            }
        }

    }
}
    /*
     * $_FILES值
     =======================
      Array (
        [file] => Array ( [name] => 20090901.xls
        [type] => application/vnd.ms-excel
        [tmp_name] => /tmp/phpZBgEGM
        [error] => 0
        [size] => 107008 )
     )

     * $info值
     =======================
    Array ( [file] => Array (
        [name] => 20090901.xls
        [type] => application/vnd.ms-excel
        [size] => 107008
        [key] => file-2
        [ext] => xls
        [md5] => be4d8d3ddc22f9f68cc47c760467b2fa
        [sha1] => 60f7f7253e4941eb8be95f3e35b3d87f49f76f21
        [savename] => 5850fa703a699.xls
        [savepath] => default/20161214/
     )

         * upload_setting 值
     =======================
    array(5) {
  ["image"] => array(2) {
    ["upload_max_filesize"] => string(5) "10240"
    ["extensions"] => string(20) "jpg,jpeg,png,gif,bmp"
  }
  ["video"] => array(2) {
    ["upload_max_filesize"] => string(5) "10240"
    ["extensions"] => string(23) "mp4,avi,wmv,rm,rmvb,mkv"
  }
  ["audio"] => array(2) {
    ["upload_max_filesize"] => string(5) "10240"
    ["extensions"] => string(11) "mp3,wma,wav"
  }
  ["file"] => array(2) {
    ["upload_max_filesize"] => string(5) "10240"
    ["extensions"] => string(63) "txt,pdf,doc,docx,xls,xlsx,ppt,pptx,zip,rar"
  }
  ["upload_max_filesize"] => array(24) {
    ["jpg"] => int(10485760)
    ["jpeg"] => int(10485760)
    ["png"] => int(10485760)
    ["gif"] => int(10485760)
    ["bmp"] => int(10485760)
    ["mp4"] => int(10485760)
    ["avi"] => int(10485760)
    ["wmv"] => int(10485760)
    ["rm"] => int(10485760)
    ["rmvb"] => int(10485760)
    ["mkv"] => int(10485760)
    ["mp3"] => int(10485760)
    ["wma"] => int(10485760)
    ["wav"] => int(10485760)
    ["txt"] => int(10485760)
    ["pdf"] => int(10485760)
    ["doc"] => int(10485760)
    ["docx"] => int(10485760)
    ["xls"] => int(10485760)
    ["xlsx"] => int(10485760)
    ["ppt"] => int(10485760)
    ["pptx"] => int(10485760)
    ["zip"] => int(10485760)
    ["rar"] => int(10485760)
  }
}
     * */

